﻿using Freebase4net.Rest;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Freebase4net
{
    public class TopicService : BaseService<TopicServiceResponse>
    {
        public TopicService(string apiKey)
            : base(apiKey)
        {

        }

        protected override string _baseUrl
        {
            get { return Constants.TopicServiceUrl; }
        }

        protected override Rest.RestClient CreateRequest(dynamic query)
        {
            RestClient client = new RestClient { BaseUrl = string.Format("{0}{1}", _baseUrl, query) };

            if (!string.IsNullOrEmpty(_apiKey))
            {
                client.AddParameter("key", _apiKey);
            }

            client.RequestFormat = DataFormat.Json;
            return client;
        }

        protected override TopicServiceResponse CreateResponse(RestResponseMessage response)
        {
            var freebaseResponse = new TopicServiceResponse
            {
                ResultAsString = response.Content,
                Status = response.StatusCode,
                ResultAsObject = JObject.Parse(response.Content)
            };

            return freebaseResponse;
        }

        public TopicServiceResponse Read(dynamic query, int limit = 10, string langauge = "/lang/en", string filter = "")
        {
            return ReadInternal(query, GetParameters(limit, langauge, filter));
        }

        public async Task<TopicServiceResponse> ReadAsync(dynamic query, int limit = 10, string langauge = "/lang/en", string filter = "")
        {
            return await ReadInternalAsync(query, GetParameters(limit, langauge, filter));
        }

        private string[] GetParameters(int limit, string langauge, string filter)
        {
            List<string> parameters = new List<string>();

            if (!string.IsNullOrEmpty(filter))
                parameters.Add(string.Format("filter,{0}", filter));
            if (limit != 10)
                parameters.Add(string.Format("limit,{0}", limit));
            if (!string.IsNullOrEmpty(langauge))
                parameters.Add(string.Format("lang,{0}", langauge));

            return parameters.ToArray();
        }
    }
}
